#include "timefreqspectrogramplot.h"

TimeFreqSpectrogramPlot::TimeFreqSpectrogramPlot(QString titleName,QCustomPlot*cp) {
    customPlot=cp;
    colorScale = new QCPColorScale(customPlot);
    customPlot->clearPlottables();
    colorMap = new QCPColorMap(customPlot->xAxis, customPlot->yAxis);
    customPlot->plotLayout()->addElement(0, 1, colorScale);
    colorMap->setColorScale(colorScale);
    colorScale->setGradient(QCPColorGradient::gpJet);  // 使用热力图渐变
    colorScale->setBarWidth(10); // 强制轴矩形最小宽度10像素
    // 坐标轴标签
    customPlot->xAxis->setLabel("Time (s)");
    customPlot->yAxis->setLabel("Frequency (Hz)");
    // 设置图表名称
    QCPTextElement *title = new QCPTextElement(customPlot); // 创建标题元素
    title->setText(titleName);                              // 设置标题文本
    title->setFont(QFont("sans", 12, QFont::Bold));         // 设置字体
    customPlot->plotLayout()->insertRow(0);                   // 在顶部插入一行
    customPlot->plotLayout()->addElement(0,  0, title);        // 将标题添加到布局中
    // 启用缩放/平移
    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectAxes);

}

TimeFreqSpectrogramPlot::~TimeFreqSpectrogramPlot()
{
    delete colorMap;
    delete customPlot;
    delete colorScale;
}

void TimeFreqSpectrogramPlot::setData(QVector<double> T, QVector<double> F, QVector<QVector<double>> psd,bool isWavlet,double max,double min)
{
    // 设置数据范围
    int rows=T.size();
    int colms=F.size();
    qDebug()<<"rows="<<rows<<",colms="<<colms;
    qDebug()<<"psd_rows="<<psd.size()<<",psdcolms="<<psd.at(0).size();
    colorMap->data()->setSize(rows,colms);
    colorMap->data()->setRange(
        QCPRange(T.first(),  T.last()),   // X轴：时间
        QCPRange(F.first(),  F.last())   // Y轴：F频率
        );
    qDebug()<<"setData1";
    for (int x=0; x<rows;  ++x){
        for (int y=0; y<colms;  ++y){
            double v=psd[x][y];
            colorMap->data()->setCell(x, y, v);
        }
    }
    qDebug()<<"setData2";
    customPlot->rescaleAxes();
    colorScale->setDataRange(QCPRange(min, max));
    customPlot->yAxis->ticker().clear();
    qDebug()<<"setData3";
    if(isWavlet)
    {
        // 创建自定义的文本刻度生成器
        // customPlot->setAutoTicks(false);
        QSharedPointer<QCPAxisTickerText> textTicker(new QCPAxisTickerText);
        textTicker->addTicks({0, 1, 2, 3, 4, 5, 6}, {"0.008", "0.016", "0.031","0.062","0.125","0.250","0.500"}); // 刻度值 + 标签文本
        // 应用到 Y 轴
        customPlot->yAxis->setTicker(textTicker);
        qDebug()<<"setData4";

    }
    qDebug()<<"setData5";
    customPlot->replot();
}

